<template>
  <n-space
    vertical
    size="large"
  >
    <n-layout-header bordered>
      <n-space justify="space-between">
        <n-gradient-text
          type="info"
          :size="24"
        >
          时间安排表:{{ showLifeModelName }}
        </n-gradient-text>
        <n-button
          @click="addNewOne()"
          type="primary"
          dashed
          >添加时间安排</n-button
        >
      </n-space>
    </n-layout-header>
    <n-layout>
      <n-layout-content content-style="padding: 24px;">
        <n-data-table
          v-show="!showEmpty"
          :columns="columns"
          :data="tableData"
          :pagination="false"
          :bordered="false"
          id="LifeItemDragTable"
          :row-props="rowProps"
        />
        <n-data-table
          v-show="showEmpty"
          :columns="columns"
          :data="[]"
          :pagination="false"
          :bordered="false"
        />
      </n-layout-content>
    </n-layout>
  </n-space>
  <n-dropdown
    placement="bottom-start"
    trigger="manual"
    :x="xRef"
    :y="yRef"
    :options="options"
    :show="showDropdownRef"
    :on-clickoutside="onClickoutside"
    @select="handleSelect"
  />
  <LifeModelItemEditDrawer v-model="editSettings"></LifeModelItemEditDrawer>
  <LifeModelDeletItem v-model="editSettings"></LifeModelDeletItem>
</template>

<script lang="ts" setup>
import LifeModelDeletItem from "./lifeModelItemsBtn/LifeModelDeletItem.vue";
import LifeModelItemEditDrawer from "./lifeModelItemsBtn/LifeModelItemEditDrawer.vue";
import { RemoveMethods } from "@/types/remove-methods";
import { TaskBoardList } from "@model/TaskBoardList";
import type { LifeModel } from "@model/lifeModel";
import type { SurfaceSetting } from "@model/surfaceSetting";
import type { TimeManageList } from "@model/timeManage";
import UseLifeModel from "@pinias/UseLifeModel";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import UseTimeManageList from "@pinias/UseTimeManageList";
import pinia from "@pinias/pinia";
import * as DateUtils from "@utils/DateUtils";
import { NButton, NDataTable, NLayout, NLayoutContent, NLayoutHeader, NSpace, useMessage } from "naive-ui";
import Sortable from "sortablejs";
import { computed, h, onMounted, reactive, ref, watch } from "vue";

// 全局数据
const { getLifeModel } = UseLifeModel(pinia);
const lifeModel: LifeModel = getLifeModel();
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
const { getTimeManageList } = UseTimeManageList(pinia);
const timeManageList: TimeManageList = getTimeManageList();
// 当前页面数据
const props = defineProps(["toRecord"]);
const showEmpty = ref(false);
const showLifeModelName = computed(() => {
  return lifeModel.getLifeModelDataById(surfaceSetting.showLifeModel)?.name;
});
const editSettings = reactive<{ toEdit: boolean; toDelete: boolean; toDealRowId: number | undefined }>({
  toEdit: false,
  toDelete: false,
  toDealRowId: undefined,
});
class RowData {
  id: number;
  startTime: number;
  startTimeStr: string;
  endTimeStr: string;
  endTime: number;
  desc: string;
  constructor(data: RemoveMethods<RowData>) {
    Object.assign(this, data);
  }
  static getNullModel() {
    return new RowData({ id: -1, startTime: 0, endTime: 0, startTimeStr: "", endTimeStr: "", desc: "" });
  }
}
// 通用方法
const getShowLifeModelData = () => {
  return lifeModel.getLifeModelDataById(surfaceSetting.showLifeModel);
};

// 渲染表格数据
const getTableData = () => {
  const result = [];
  const chooseLife = getShowLifeModelData();
  if (chooseLife !== undefined) {
    const list = chooseLife.timeManageList;
    for (var i = 0; i < list.length; i++) {
      const id = list[i];
      const oldDdata = timeManageList.getTimeManageById(id);
      if (oldDdata !== undefined) {
        result.push(
          new RowData({
            id: oldDdata.id,
            startTime: oldDdata.startTime,
            startTimeStr: DateUtils.timestampToTime(oldDdata.startTime),
            endTimeStr: DateUtils.timestampToTime(oldDdata.endTime),
            endTime: oldDdata.endTime,
            desc: oldDdata.desc,
          }),
        );
      }
    }
    // console.log('computed',result);
  }
  if (result.length === 0) {
    result.push(RowData.getNullModel());
    showEmpty.value = true;
  } else showEmpty.value = false;
  return result;
};
const tableData = ref(getTableData());
watch(showLifeModelName, () => {
  surfaceSetting.LifeModelItemsKey = new Date().getTime();
  // tableData.value = getTableData()
});
// 渲染表头
const createColumns = () => {
  return [
    {
      title: "开始时间",
      key: "startTimeStr",
      resizable: true,
    },
    {
      title: "结束时间",
      key: "endTimeStr",
      resizable: true,
    },
    {
      title: "描述",
      key: "desc",
      resizable: true,
    },
    {
      title: "Action",
      key: "actions",
      render(row: RowData) {
        const btns = [
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: "small",
              id: "handle-drag",
              onClick: () => play(row),
            },
            { default: () => "上下移动" },
          ),
        ];
        if (props.toRecord)
          btns.push(
            h(
              NButton,
              {
                strong: true,
                tertiary: true,
                size: "small",
                id: "handle-drag",
                onClick: () => record(row),
              },
              { default: () => "计时" },
            ),
          );
        return btns;
      },
    },
  ];
};
const columns = createColumns();
const play = (row: RowData) => {
  console.log(row);
};
const record = (row: RowData) => {
  // message.info(`Play ${row.title}`);
  if (TaskBoardList.beginRecord(surfaceSetting.taskBoardList, row.id, 2)) message.success("开始计时");
  else message.error("存在计时的任务");
};
const message = useMessage();
// 右键菜单
const rowProps = (row: RowData) => {
  return {
    onContextmenu: (e: MouseEvent) => {
      // message.info(JSON.stringify(row, null, 2));
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
      // console.log('rowProps',row)
      editSettings.toDealRowId = row.id;
    },
  };
};
const options = [
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "删除"),
    key: "delete",
  },
];
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
const onClickoutside = () => {
  showDropdownRef.value = false;
};
const handleSelect = (key: string, node: string) => {
  console.log(key, node);
  showDropdownRef.value = false;
  if (key == "edit") {
    editSettings.toEdit = true;
  }
  if (key == "delete") {
    editSettings.toDelete = true;
  }
};
const addNewOne = () => {
  editSettings.toDealRowId = undefined;
  editSettings.toEdit = true;
};
// 拖拽逻辑
function setSort() {
  const el = document.querySelector("#LifeItemDragTable table tbody");
  //console.log('el',el);
  new Sortable(el, {
    handle: "#handle-drag",
    sort: true,
    ghostClass: "sortable-ghost",
    onEnd: (e: any) => {
      const chooseLife = getShowLifeModelData();
      const targetRow = chooseLife?.timeManageList.splice(e.oldIndex, 1)[0];
      if (targetRow !== undefined) chooseLife?.timeManageList.splice(e.newIndex, 0, targetRow);
    },
  });
}
onMounted(() => {
  setSort();
});
</script>
